# -*- coding: utf-8 -*-
# @Author   : xiongjianwen
# @Time     : 2023/1/5 16:17
# @File     : handle_images.py
# @Project  : BwProCost_Auto_v1
import numpy as np
import pyscreenshot as pyscreenshot
from PIL import Image
from PIL import ImageChops,ImageGrab
from skimage.metrics import structural_similarity
import imutils
import cv2
import allure
# path_one 图片一的路径# path_two 图片二的路径# diff_save_location 不同之处的图片的存储路径

def compare_images_old(path_one, path_two, diff_save_location,img_doc='异常图片'):
    import warnings
    warnings.warn('this method has been deprecated,please use compare_images instead!', DeprecationWarning)
    image_one = Image.open(path_one)
    image_two = Image.open(path_two)
    diff = ImageChops.difference(image_one, image_two)
    if diff.getbbox() is None:
        # 图片间没有任何不同则直接退出d
        print("我们是一模一样的图片")
        return True
    else:
        diff.save(diff_save_location)
        with open(diff_save_location, 'rb') as f:
            file = f.read()
        allure.attach(file, img_doc, allure.attachment_type.JPG)  # 图片对比不同，把图片放在allure报告中
        return False

def compare_images(path_one, path_two, diff_save_location,img_doc='异常图片'):
    """
    注意：路径中不要带中文！！！！---不带中文的问题已解决
    :param path_one:
    :param path_two:
    :param diff_save_location:
    :param img_doc:
    :return:
    """
    # 加载两张图片并将他们转换为灰度
    # imageA = cv2.imread(path_one)
    # imageB = cv2.imread(path_two)
    imageA = cv2.imdecode(np.fromfile(path_one,dtype=np.uint8),-1) # 解决中文问题，弃用前面2行代码
    imageB = cv2.imdecode(np.fromfile(path_two,dtype=np.uint8),-1)

    grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

    # 计算两个灰度图像之间的结构相似度指数
    (score, diff) = structural_similarity(grayA, grayB, full=True)
    diff = (diff * 255).astype("uint8")
    # print("SSIM:{}".format(score))
    if score == 1: # 相似度等于1的时候，图片一模一样，否则图片不同
        print('我们是一模一样的图片')
        return True
    else:
        # 找到不同点的轮廓以致于我们可以在被标识为“不同”的区域周围放置矩形
        thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        # cnts = cnts[0] if imutils.is_cv2() else cnts[1]
        cnts = cnts[0] if imutils.is_cv4() else cnts[1]

        # 找到一系列区域，在区域周围放置矩形
        for c in cnts:
            (x, y, w, h) = cv2.boundingRect(c)
            # if w>30 or h>30:
            cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
            cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
        # 用cv2.imshow 展现最终对比之后的图片， cv2.imwrite 保存最终的结果图片
        # cv2.imshow("Modified", imageB)
        # cv2.imwrite(diff_save_location, imageB)
        cv2.imencode('.jpg',imageB)[1].tofile(diff_save_location) # 解决保存中文问题，弃用前面一行
        cv2.waitKey(0)
        with open(diff_save_location, 'rb') as f:
            file = f.read()
        allure.attach(file, img_doc, allure.attachment_type.JPG)  # 图片对比不同，把图片放在allure报告中
        return False


def snapshot_images(bbox,savePath,img_doc='当前截图',allure_attach=True):
    # 参数说明
    # 第一个参数 开始截图的x坐标
    # 第二个参数 开始截图的y坐标
    # 第三个参数 结束截图的x坐标
    # 第四个参数 结束截图的y坐标
    # bbox = (32, 126, 1920, 1002)
    image = pyscreenshot.grab(bbox=bbox)
    image.save(savePath)
    # im = ImageGrab.grab(bbox)  # PIL截图质量差-已淘汰
    # # 参数 保存截图文件的路径
    # im.save(savePath)
    if allure_attach:
        with open(savePath, 'rb') as f: # 截图同时附在allure报告中，如果不需要就注释
            file = f.read()
        allure.attach(file, img_doc, allure.attachment_type.JPG) # 区域截图的同时，会把截图放到allure报告中


if __name__ == '__main__':
    compare_images('../data/images_compare/test2.jpg', '../data/images_compare/GT1-1基本信息对比图.jpg', '../data/images_compare/test_不同之处.jpg')